import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';

import { Viewer } from '@photo-sphere-viewer/core';
import { MarkersPlugin } from '@photo-sphere-viewer/markers-plugin';

import '@photo-sphere-viewer/core/index.css';
import '@photo-sphere-viewer/markers-plugin/index.css';

const baseUrl = 'https://photo-sphere-viewer-data.netlify.app/assets/';

const PSViewer: React.FC = () => {
  const ref = useRef<any>();
  const [viewer, setViewer] = useState<Viewer>();

  // init psv
  useLayoutEffect(() => {
    if (!ref.current) return;

    // 初始化实景
    const PSViewer = new Viewer({
      container: ref.current,
      panorama: './img.webp',
      plugins: [MarkersPlugin],
    });

    // 绑定marker点击事件
    const markersPlugin = PSViewer.getPlugin<MarkersPlugin>(MarkersPlugin);
    markersPlugin.addEventListener('select-marker', (evt) => {
      //
      console.log(evt);
    });

    setViewer(PSViewer);

    return () => {
      setViewer(undefined);
      PSViewer.destroy();
    };
  }, []);

  // update markers
  useEffect(() => {
    if (!viewer) return;
    const markersPlugin = viewer.getPlugin<MarkersPlugin>(MarkersPlugin);

    markersPlugin.setMarkers([
      {
        id: 'marker-1',
        position: { pitch: 0.11, yaw: -0.35 },
        image: baseUrl + 'pictos/pin-blue.png',
        size: { width: 32, height: 32 },
        anchor: 'bottom center',
        tooltip: 'Default scaling',
      },
      {
        id: 'marker-2',
        position: { pitch: 0.32, yaw: 0.11 },
        image: baseUrl + 'pictos/pin-red.png',
        size: { width: 32, height: 32 },
        anchor: 'bottom center',
        tooltip: 'Disable scaling',
        hoverScale: false,
      },
      {
        id: 'marker-3',
        position: { pitch: -0.05, yaw: 0.04 },
        image: baseUrl + 'pictos/pin-red.png',
        size: { width: 32, height: 32 },
        anchor: 'bottom center',
        tooltip: 'Custom scaling',
        hoverScale: { amount: 3, easing: 'ease-in-out', duration: 1000 },
      },
    ]);
  }, [viewer]);

  return <div className="w-full h-full" ref={ref}></div>;
};

export default PSViewer;
